<template>
  <div :class="{'mobile-create': showMobilePage}" class="create-energy-wrap">
    <explanation :explanation="explanationObj" is-expand class="explanation" style="margin: 0;"/>
    <el-form ref="energyForm" :rules="rules" :model="energyInfo" :label-position="formAlign" class="energy-form" label-width="110px">
      <div class="energy-info" style="padding-bottom: 0;">
        <Title title="创建信息" font-size="16px" style="margin: 0 0 16px"/>
        <el-row class="flex-wrap" type="flex">
          <el-col :span="12">
            <el-form-item label="申请人" prop="proposerId">
              <selectWithUserLoad
                v-model="proposerObj"
                :show-check-user="true"
                :default-list="defaultProposerList"
                :class="{'w240':showMobilePage, 'width-240': !showMobilePage}"
                value-type="object"
                key-name="id"
                label-name="userName"
                filterable
                placeholder="请选择申请人"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请人部门" prop="proposerDepartmentId">
              <el-cascader
                v-model="energyInfo.proposerDepartmentId"
                :show-all-levels="false"
                :options="deptList"
                :props="{
                  emitPath:false,
                  value: 'id',
                  label: 'name',
                  checkStrictly: true,
                  multiple: false,
                }"
                placeholder="请选择申请人部门"
                size="small"
                collapse-tags
                filterable
                clearable>
                <template slot-scope="{ data }">
                  <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                    <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                    <span class="inline-tag ellipsisOne">{{ data.name }}</span>
                  </el-tooltip>
                  <span v-else>{{ data.name || '--' }}</span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建人" prop="creatorName">
              <el-input
                v-model="energyInfo.creatorName"
                :class="{'w240':showMobilePage}"
                size="small"
                disabled
                name="creatorName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建人部门" prop="departmentName">
              <el-input
                v-model="energyInfo.departmentName"
                :class="{'w240':showMobilePage}"
                size="small"
                disabled
                name="departmentName" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="energy-info" style="padding-top: 0;">
        <Title title="基本信息" font-size="16px" style="margin: 0 0 16px"/>
        <el-row :class="{'flex-wrap':showMobilePage}" type="flex">
          <el-col :span="12">
            <el-form-item label="月份" prop="monthTime">
              <el-date-picker
                v-model="energyInfo.monthTime"
                name="monthTime"
                type="month"
                size="small"
                placeholder="选择月份"
                value-format="timestamp"
                format="yyyy/MM"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="填写人员">
              <select-user v-model="energyInfo.userList" :diy-user-item-list.sync="energyInfo.userItemList" placeholder="请选择"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="energyInfo.remark" :class="{'w240':showMobilePage}" type="textarea" name="remark" maxlength="500" placeholder="请输入备注说明" resize="none"/>
        </el-form-item>
      </div>
    </el-form>

    <!-- 2.9.7修改成弹窗，修改时流程可以被编辑 -->
    <audit-process
      ref="auditProcess"
      v-model="auditInfo"
      :loading="loading"
      :flow-structure="processDetail"
      :default-aduitor-list="defaultProposerList"
      :old-audit-info="oldAuditInfo"
      :is-modify="Boolean(remodifyId)"
      :disable="Boolean(remodifyId)"
      :is-modify-form="Number(isModifyForm)"
      :current-process-index="Number(currentProcessIndex)"
      @submit="submit"
      @getProcess="getProcess"
    />
    <fixed-pagination>
      <div class="center">
        <el-button v-if="(!reapplyId && !remodifyId) || createNew" type="info" size="small" class="back-btn empty-btn-style" @click="saveDraft">保存草稿</el-button>
        <el-button type="primary" size="small" class="submit-btn" @click="openDrawer">发起审批</el-button>
        <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">返回</el-button>
      </div>
    </fixed-pagination>
  </div>
</template>
<script>
import Title from '@/components/Title';
import AuditProcess from '@/components/Common/auditProcess';
import SelectUser from '@/views/energy/components/selectUser';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import explanation from '@/components/Common/explanation';
import { showModal } from '@/utils/message';
import { createAuditStructure } from '@/utils/aduitor';
import { mapState } from 'vuex';
import { isContained } from '@/utils/tools';
import mobileCreate from '@/mixins/mobileCreate';

// api
import { energyCreate, energyEdit, energyInfo, formSubmit } from '@/api/energy';
import { getDepartmentAll } from '@/api/config';
import { processManagementDetail } from '@/api/legal';
import processCreate from '@/mixins/processCreate';
export default {
  components: { Title, AuditProcess, SelectUser, explanation, selectWithUserLoad },
  mixins: [processCreate, mobileCreate],
  data() {
    return {
      antiShakeTime: 0, // 防抖时间
      energyId: '', // 精力分配标识符
      energyInfo: {// 基本信息
        monthTime: '',
        userList: [],
        userItemList: [],
        remark: '',
        proposerId: '',
        proposer: '',
        proposerDepartmentId: '',
        proposerDepartmentName: '',
        creatorId: '',
        creatorName: '',
        departmentName: '',
        departmentId: ''
      },
      remodifyId: null, // 审批修改
      reapplyId: null, // 重新申请
      processDetail: null,
      auditInfo: {// 流程信息
        activeTime: null,
        isSigner: 0,
        countersignSet: 0,
        process: [],
        senders: [],
        id: null
      },
      explanationObj: {
        content: '',
        styConfig: ''
      }, // 审批说明
      rules: {
        'proposerDepartmentId': [{ required: true, message: '请选择申请部门', trigger: 'change' }],
        'proposerId': [{ required: true, message: '请选择申请人', trigger: 'change' }],
        monthTime: [{ required: true, trigger: 'change', validator: this.validateTime('请选择月份') }]
      },
      deptList: [],
      loading: false,
      oldAuditInfo: null// 保存旧流程用于比较，修改的情况需要判断流程是否发生变动
    };
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'energyDetail') {
      to.meta.isDetail = true;
    } else {
      to.meta.isDetail = false;
    }
    next();
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    defaultProposerList() {
      if (this.energyInfo.proposerId && this.energyInfo.proposer) {
        return [{
          id: this.energyInfo.proposerId,
          userName: this.energyInfo.proposer
        }];
      }
      return [];
    },
    proposerObj: {
      get() {
        return {
          id: this.energyInfo.proposerId,
          userName: this.energyInfo.proposer
        };
      },
      set(data) {
        this.energyInfo.proposerId = data.id;
        this.energyInfo.proposer = data.userName;
      }
    },
    processStructure() {
      if (!this.processDetail) return [];
      return this.processDetail.process;
    }
  },
  created() {
    this.getDeptList();
    this.createNew = Number(this.$route.query.createNew) || 0;
    this.energyId = Number(this.$route.query.energyId) || '';
    this.reapplyId = this.$route.query.reapplyId || null;
    this.remodifyId = this.$route.query.remodifyId || null;
    if (this.energyId) {
      this.getEnergyInfo();
      this.reapplyId && this.getExplanation();
    } else {
      this.getExplanation();
      this.initData();
    }
  },
  methods: {
    initData() {
      // 回填创建人、申请人、创建人部门、申请人部门
      this.$set(this.energyInfo, 'proposerId', this.userInfo.id);
      this.$set(this.energyInfo, 'proposer', this.userInfo.userName);
      this.$set(this.energyInfo, 'creatorId', this.userInfo.id);
      this.$set(this.energyInfo, 'creatorName', this.userInfo.userName);
      if (this.userInfo.deptName && this.userInfo.deptName.length) {
        this.$set(this.energyInfo, 'departmentId', this.userInfo.deptName[0].id);
        this.$set(this.energyInfo, 'departmentName', this.userInfo.deptName[0].name);
        this.$set(this.energyInfo, 'proposerDepartmentId', this.userInfo.deptName[0].id);
        this.$set(this.energyInfo, 'proposerDepartmentName', this.userInfo.deptName[0].name);
      }
    },
    validateTime(msg) {
      return (rule, value, callback) => {
        if (!value) { callback(new Error(msg)); } else { callback(); }
      };
    },
    // 信息获取
    async getEnergyInfo() {
      try {
        const res = await energyInfo(this.energyId);
        if (res.code !== 200) { this.$message.error(res.message); return; }
        // 回填创建人、申请人、创建人部门、申请人部门
        this.$set(this.energyInfo, 'proposerId', res.data.proposerId || '');
        this.$set(this.energyInfo, 'proposer', res.data.proposer || '');
        this.$set(this.energyInfo, 'creatorId', res.data.creatorId);
        this.$set(this.energyInfo, 'creatorName', res.data.creatorName);
        this.$set(this.energyInfo, 'departmentId', res.data.departmentId);
        this.$set(this.energyInfo, 'departmentName', res.data.departmentName);
        this.$set(this.energyInfo, 'proposerDepartmentId', res.data.proposerDepartmentId);
        this.$set(this.energyInfo, 'proposerDepartmentName', res.data.proposerDepartmentName);

        const user = res.data.personnelInfo;
        const unfilledList = user.unfilledList || [];
        const finishedList = user.finishedList || [];
        const userItemList = [...unfilledList, ...finishedList];// 未填加已填
        this.energyInfo.userList = userItemList.map(e => e.id);
        this.energyInfo.userItemList = JSON.parse(JSON.stringify(userItemList).replace(/value/g, 'userName'));
        this.energyInfo.remark = res.data.remark;
        this.version = Number(res.data.version) || 0;
        if (res.data.month) {
          const month = `${res.data.month.replace(/-/g, '/')}/01`;
          this.energyInfo.monthTime = new Date(month).getTime();
        }
        if (res.data.auditInfo && !this.reapplyId) {
          this.oldAuditInfo = Object.assign({}, res.data.auditInfo);
          this.auditInfo = JSON.parse(JSON.stringify(res.data.auditInfo));
          this.processDetail = JSON.parse(JSON.stringify(res.data.auditInfo));
        } else {
          this.getExplanation();
        }
      } catch (err) {
        console.log(err);
      }
    },
    getDeptList() {
      getDepartmentAll().then(res => {
        this.deptList = (res && res.data) || [];
      });
    },
    // 获取流程详情
    getProcessDetail(isRefresh = false) {
      this.loading = true;
      const data = {
        type: 12,
        energyInfo: JSON.parse(JSON.stringify(this.energyInfo))
      };
      formSubmit(data).then(res => {
        this.loading = false;
        if (res.code === 200) {
          const data = res.data;
          if (this.remodifyId && !isRefresh) {
            this.isProcessChange(data, this.oldAuditInfo) && this.$refs['auditProcess'].setShowRefresh(true);
          } else {
            this.processDetail = data;
            this.auditInfo.activeTime = data.activationTime;
            this.auditInfo.id = data.id;
            const proposer = {
              id: this.energyInfo.proposerId,
              userName: this.energyInfo.proposer
            };
            if (this.userInfo.id === this.energyInfo.proposerId) {
              proposer.avatar = this.userInfo.avatar;
            }
            // 创建人回填
            this.auditInfo.process = createAuditStructure(data.process, this.userInfo, proposer);
            this.auditInfo.senders = data.senderDiyUserList || [];
          }
          if (this.remodifyId && isRefresh) { // 修改刷新保存刷新后流程用于对比
            this.oldAuditInfo = Object.assign({}, data);
            this.oldAuditInfo.process.forEach(el => {
              this.oldAuditInfo.templateNodeId = el.id;
            });
            this.oldAuditInfo.activeTime = data.activationTime * 1000;
          }
          this.$refs['auditProcess'].openDrawer();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.loading = false;
        console.log(err);
      });
    },
    isProcessChange(nowAuditInfo = {}, oldAuditInfo = {}) {
      if (nowAuditInfo.activationTime !== (oldAuditInfo.activeTime / 1000)) {
        return true;
      }
      const nowProcessIds = nowAuditInfo && nowAuditInfo.process.map(el => el.id) || [];
      const oldProcessIds = oldAuditInfo && oldAuditInfo.process.map(el => el.templateNodeId) || [];
      if (!isContained(nowProcessIds, oldProcessIds)) {
        return true;
      }
      return false;
    },
    getExplanation() { // 获取审批说明
      processManagementDetail({ id: 3527, type: 12 }).then(res => {
        // 审批说明
        const data = res.data[0];
        this.explanationObj.content = data.explanation || '';
        this.explanationObj.styConfig = data.styConfig || '';
      }).catch(err => {
        console.log(err);
      });
    },
    saveDraft() {
      if (!this.energyId || this.createNew) {
        this.energyCreate(1, '保存草稿成功');// 1为保存草稿
      } else {
        this.energyEdit(1);
      }
    },
    getProcess() {
      this.getProcessDetail(true);
      this.isRefresh = true;
    },
    openDrawer() { // 2.9.7 流程弹窗
      this.$refs['energyForm'].validate(valid => {
        if (valid) { // 表单校验通过，则仅提交表单部分，不提交流程信息，用来获取最新流程
          this.getProcessDetail();
        }
      });
    },
    submit(senders = []) {
      this.modifySenders = senders;// 存到mixins
      if (this.isModifyForm) { // 节点修改走编辑的逻辑
        this.energyEdit(2);
        return;
      }
      showModal('提交申请后无法进行修改?', '', {
        iconClass: 'del-icon'
      }).then(() => {
        if (!this.energyId || this.reapplyId) { // 重新提交也是新建
          this.energyCreate(2, '新建精力分配成功');
        } else {
          this.energyEdit(2);
        }
      }).catch(() => {
        return false;
      });
    },
    energyEdit(submitType) { // 1草稿编辑 2为详情编辑
      const data = {
        isEditAudit: false
      };
      data.energyInfo = JSON.parse(JSON.stringify(this.energyInfo));
      data.auditInfo = JSON.parse(JSON.stringify(this.auditInfo));
      data.submitType = submitType;
      this.handleModifyData(data);
      if (this.remodifyId && this.isRefresh) {
        data.isEditAudit = true;// 修改时，流程被编辑或者更新
      }
      energyEdit(this.energyId, data).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
        }
        if (res.data.id && res.data.processId) {
          this.$router.push({
            name: 'energyDetail',
            query: {
              energyId: res.data.id,
              processId: res.data.processId
            }
          });
        } else {
          this.$router.push({
            name: 'energy'
          });
        }
      }).catch(err => {
        if (err.code === 502 && !this.remodifyId) { // 503 表示流程状态已变更
          this.$refs['auditProcess'].setShowRefresh(true);
          console.log(err);
        }
        if (err.code === 505) { // 节点修改跳转详情
          this.nodeModifyJumpDetail({ routeName: 'energyDetail', params: {}, query: { energyId: this.energyId, processId: this.remodifyId }});
        }
      });
    },
    energyCreate(submitType, message) { // 1草稿 2为保存提交 3重新申请
      var timestamp = Date.parse(new Date());
      if (timestamp - this.antiShakeTime < 500) {
        return;
      }
      this.antiShakeTime = timestamp;
      const data = {
        isEditAudit: false
      };
      data.energyInfo = this.energyInfo;
      data.auditInfo = this.auditInfo;
      data.submitType = submitType;
      if (this.reapplyId && !this.createNew) {
        data.submitType = 3;
        this.energyId = null;
        // data.byReapplyId = this.energyId;//精力分配无关联信息，暂不传原id
      }
      if (this.createNew) {
        delete data.id;
      }
      energyCreate(data).then(res => {
        if (res.code !== 200) { this.$message.error(res.message); return; }
        this.$message.success(message);
        if (submitType === 2) {
          this.$router.push({
            name: 'energyDetail',
            query: {
              energyId: res.data.id,
              processId: res.data.processId
            }
          });
          return;
        } else {
          this.$router.push({
            name: 'energy'
          });
        }
      }).catch(err => {
        if (err.code === 502 && !this.remodifyId) {
          this.$refs['auditProcess'].setShowRefresh(true);
          console.log(err);
        }
      });
    },
    toBack() {
      if (this.remodifyId) {
        this.processId = this.remodifyId;
      }
      if (this.reapplyId) {
        this.processId = this.reapplyId;
      }
      if (this.$route.meta.isDetail) {
        this.$router.push({
          name: 'energyDetail',
          query: {
            energyId: this.energyId,
            processId: this.processId
          }
        });
        return;
      }
      this.$router.push({
        name: 'energy'
      });
    }
  }
};
</script>
<style lang="scss" scoped>
	.create-energy-wrap{
		margin: 16px;
		background: #FFFFFF;
		min-height: calc(100vh - 56px);
    .energy-info{
      padding: 20px 24px 24px;
    }
    .empty-btn-style {
      border-color: #406EFF;
      background: #fff;
      color: #406EFF;
      width: 80px;
      padding: 7px 0;
      text-align: center;
    }
    &::v-deep {
      .el-input__inner{
        width: 240px;
      }
      .shadow {
        padding-left: 17px !important;
      }
      .el-textarea .el-textarea__inner{
        width: 240px;
        height: 88px;
      }
    }
	}
.flex-wrap {
  flex-wrap: wrap;
  &::v-deep {
    .el-date-picker, .select-custom-user-wrap {
      width: 100% !important;
    }
  }
}
.w240 {
  &::v-deep .el-textarea__inner{
    width: 100% !important;
  }
}
.width-240 {
  width: 240px
}
</style>
